package com.heihx.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heihx.constant.MessageConstant;
import com.heihx.constant.StatusConstant;
import com.heihx.dto.DishDTO;
import com.heihx.dto.DishPageQueryDTO;
import com.heihx.entity.Dish;
import com.heihx.entity.DishFlavor;
import com.heihx.entity.Setmeal;
import com.heihx.exception.DeletionNotAllowedException;
import com.heihx.mapper.DishMapper;
import com.heihx.result.PageResult;
import com.heihx.service.DishFlavorService;
import com.heihx.service.DishService;
import com.heihx.service.SetMealDishService;
import com.heihx.service.SetMealService;
import com.heihx.vo.DishVO;
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private SetMealDishService setMealDishService;

    @Autowired
    private SetMealService setMealService;

    /**
     * 新增菜品和对应口味
     * @param dishDTO
     */
    @Override
    @GlobalTransactional
    public void saveWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //插入数据并获取返回的主键值
        dishMapper.insert(dish);
        Long id = dish.getId();

        List<DishFlavor> flavors = dishDTO.getFlavors();
        if(flavors != null && flavors.size() > 0){
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(id);
            });
            dishFlavorService.saveBatch(flavors);
        }
    }

    /**
     * 菜品批量删除
     * @param ids
     */
    @Override
    @GlobalTransactional
    public void deleteByIds(List<Long> ids) {
        //判断菜品是否启售
        for (Long id : ids){
            Dish dish = getById(id);
            if (dish.getStatus() == StatusConstant.ENABLE){
                //菜品处于启售状态，无法删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        //菜品是否被套餐关联
        List<Long> setMealIds = setMealDishService.getSetMealIdsByDishIds(ids);
        if (setMealIds != null && setMealIds.size() > 0){
            //当前菜品被套餐关联了，不能删除
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        //删除菜品和对应口味数据
        removeBatchByIds(ids);
        dishFlavorService.removeBatchByDishIds(ids);

    }

    /**
     * 分页查询菜品
     * @param dishPageQueryDTO
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        //创建分页对象
        Page<Dish> page = Page.of(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        String name = dishPageQueryDTO.getName();
        Integer categoryId = dishPageQueryDTO.getCategoryId();
        Integer status = dishPageQueryDTO.getStatus();

        //构建查询条件
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<Dish>()
                .like(StringUtils.isNotBlank(name), Dish::getName, name)
                .eq(categoryId != null, Dish::getCategoryId, categoryId)
                .eq(status != null, Dish::getStatus, status);

        page(page,wrapper);
        return new PageResult(page.getTotal(),page.getRecords());
    }

    /**
     * 根据id查询菜品和对应口味
     * @param id
     * @return
     */
    @Override
    public DishVO getByIdWithFlavor(Long id) {
        Dish dish = getById(id);
        //根据菜品ID查询口味数据
        List<DishFlavor> dishFlavors = dishFlavorService.getByDishId(id);
        //组装VO
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish,dishVO);
        dishVO.setFlavors(dishFlavors);

        return dishVO;
    }

    /**
     * 修改菜品和对应口味
     * @param dishDTO
     */
    @Override
    @GlobalTransactional
    public void updateWithFlavor(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO,dish);
        //修改菜品表信息
        updateById(dish);
        //删除原有口味信息
        dishFlavorService.removeBatchByDishIds(Collections.singletonList(dishDTO.getId()));
        //重新插入口味信息
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0){
            dishFlavorService.saveBatch(flavors);
        }
    }

    /**
     * 菜品起售停售
     * @param status
     * @param id
     */
    @Override
    @GlobalTransactional
    public void startOrStop(Integer status, Long id) {
        //修改状态
        lambdaUpdate()
                .eq(Dish::getId,id)
                .set(Dish::getStatus,status)
                .update();

        if(status == StatusConstant.DISABLE){
            //停售套餐
            List<Long> setMealIds = setMealDishService.getSetMealIdsByDishIds(Collections.singletonList(id));
            if(setMealIds != null && setMealIds.size() > 0){
                List<Setmeal> setmeals = new ArrayList<>();
                for (Long setMealId : setMealIds){
                    Setmeal setmeal = Setmeal.builder()
                            .id(setMealId)
                            .status(StatusConstant.DISABLE)
                            .build();
                    setmeals.add(setmeal);
                }
                setMealService.updateBatchById(setmeals);
            }
        }
    }

    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = lambdaQuery()
                .eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId())
                .eq(dish.getStatus() != null, Dish::getStatus, dish.getStatus())
                .list();

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList){
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorService.lambdaQuery()
                    .eq(DishFlavor::getDishId, d.getId())
                    .list();

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }
        return dishVOList;
    }
}
